package com.fox0g.filter;

import org.springframework.stereotype.Service;

import java.util.Arrays;

//中值滤波法
@Service
public class MedianFilter {
    private double[] buffer;
    private int bufferIndex;

    public MedianFilter() {
        this.buffer = new double[5];
        this.bufferIndex = 0;
    }

    public double filter(double newValue) {
        // 从缓冲区中移除旧值
        double oldValue = buffer[bufferIndex];
        buffer[bufferIndex] = newValue;

        // 更新缓冲区索引
        bufferIndex = (bufferIndex + 1) % buffer.length;

        // 对缓冲区数据进行排序,并返回中值
        Arrays.sort(buffer);
        return buffer[buffer.length / 2];
    }
}

//int型
//class MedianFilter {
//    private int[] buffer;
//    private int bufferIndex;
//
//    public MedianFilter(int bufferSize) {
//        this.buffer = new int[bufferSize];
//        this.bufferIndex = 0;
//    }
//
//    public int filter(int newValue) {
//        // 从缓冲区中移除旧值
//        int oldValue = buffer[bufferIndex];
//        buffer[bufferIndex] = newValue;
//
//        // 更新缓冲区索引
//        bufferIndex = (bufferIndex + 1) % buffer.length;
//
//        // 对缓冲区数据进行排序,并返回中值
//        Arrays.sort(buffer);
//        return buffer[buffer.length / 2];
//    }
//}
